<?php


namespace App\Repositories;


use App\Exceptions\BasicException;
use Illuminate\Support\Facades\DB;

class MallProductSubCateRepository
{
    public function addOrEditProductSubCate($param)
    {
        //参数提取
        $id = $param['id'] ?? 0;
        $subCateName = $param['sub_cate_name'];
        $pCateIds = explode(',', $param['p_cate_ids']);
        $status = $param['status'];

        //参数验证
        $nameExist = app('model_mall_sub_category')
            ->select('id')
            ->where('name', $subCateName)
            ->where(function ($query) use ($id) {
                if ($id > 0) {
                    $query->where('id', '<>', $id);
                }
            })->first();
        if ($nameExist) throw new BasicException(0, '子分类名称已经存在');

        $queryPCateIds = app('model_mall_categories')->select('id')->whereIn('id', $pCateIds)->pluck('id')->toArray();
        if (count($pCateIds) != count($queryPCateIds)) {
            throw new BasicException(0, '父分类id错误');
        }

        //入库或修改
        DB::beginTransaction();
        try {
            $data = [
                'name' => $subCateName,
                'status' => $status,
            ];

            if ($id > 0) {
                $subCate = app('model_mall_sub_category')->select('id')->where('id', $id)->first();
                if (empty($subCate)) throw new BasicException(0, '子分类id错误');

                //查询原始父分类id
                $originalPCateIds = app('model_mall_category_join')->select('category_id')->where('sub_category_id', $id)->pluck('category_id')->toArray();

                app('model_mall_sub_category')->where('id', $id)->update($data);

            } else {

                $originalPCateIds = [];
                $id = app('model_mall_sub_category')->insertGetId($data);
            }

            //要新增的分类关联
            $insertPCateIds = array_diff($pCateIds, $originalPCateIds);
            foreach ($insertPCateIds as $insertPCateId) {
                app('model_mall_category_join')->insert([
                    'category_id' => $insertPCateId,
                    'sub_category_id' => $id,
                ]);
            }
            //要删除的分类关联
            $delPCateIds = array_diff($originalPCateIds, $pCateIds);
            foreach ($delPCateIds as $delPCateId) {
                app('model_mall_category_join')->where([
                    'category_id' => $delPCateId,
                    'sub_category_id' => $id,
                ])->delete();
            }

            DB::commit();
            return true;
        } catch (\Exception $e) {
            DB::rollBack();
            throw new BasicException(0, $e->getMessage());
        }
    }
}